<?php 

$SessClass = new Session();

//// Set the session handlers
// NOTE: the class is passed by reference! 
session_set_save_handler (array(&$SessClass, '_open'), 
                          array(&$SessClass, '_close'), 
                          array(&$SessClass, '_read'), 
                          array(&$SessClass, '_write'), 
                          array(&$SessClass, '_destroy'), 
                          array(&$SessClass, '_gc')); 

//// Set the session name
session_name('osCsid');

//// Simple logic to see if the osCsid is passed via GET or POST
if (isset($_POST[session_name()])) {
	session_id($_POST[session_name()]);
} elseif ( isset($_GET[session_name()]) ) {
	session_id($_GET[session_name()]);
}

//// If the visitor has cookies disabled and the osCsid is set via GET or POST
// start the output buffer and rewrite the page links / forms
if ( !isset($_COOKIE[session_name()]) && ( isset($_GET[session_name()]) || isset($_POST[session_name()]) ) ){
	output_add_rewrite_var(session_name(), session_id());
}

//// Finally, start the session
session_start(); 


class Session{ 
	/**
 	* $session_table is the database table used to store session data.  This is set as the defined constant in includes/database_tables.php
	* @var string 
 	*/
    var $session_table; 
	/**
 	* $connection is the method used to store session data.  Currently, the only supported method is "mysql".
	* @var string
 	*/
    var $connection; 
	/**
 	* $db_host is the database host setting which is set by the defined constant in includes/configure.php
	* @var string 
 	*/
    var $db_host; 
	/**
 	* $db_use is the database user setting which is set by the defined constant in includes/configure.php
	* @var string 
 	*/
    var $db_user; 
	/**
 	* $db_pass is the database password setting which is set by the defined constant in includes/configure.php
	* @var string 
 	*/
    var $db_pass; 
	/**
 	* $db_dbase is the database name setting which is set by the defined constant in includes/configure.php
	* @var string 
 	*/
    var $db_dbase; 
	/**
 	* $DB is the database object
	* @var object
 	*/
	var $DB;
	/**
 	* $session_lifetime is the session lifetime value: default 1440
	* @var integer 
 	*/
	var $session_lifetime;


	function Session($server = DB_SERVER, $username = DB_SERVER_USERNAME, $database = DB_DATABASE, $password = DB_SERVER_PASSWORD){
		$this->db_dbase = $database;
		$this->db_user = $username;
		$this->db_pass = $password;
		$this->db_host = $server;
		$this->session_table = defined('TABLE_SESSIONS') ? TABLE_SESSIONS : 'sessions';
		$this->connection = defined('STORE_SESSIONS') ? STORE_SESSIONS : 'mysql';
		if ($this->connection == 'mysql'){
			$this->DB = new MySQL_Database($this->db_host, $this->db_user, $this->db_dbase, $this->db_pass);
		}
	    if (!$this->session_lifetime = get_cfg_var('session.gc_maxlifetime')) {
			$this->session_lifetime = 1440;
		}
	} # end class constructor


    function _open($path, $name) { 
        return true; 
    } # end function 

    function _close() { 
        $this->_gc(); 
        return true; 
    } # end function


    function _read($sesskey) { 
        $sql = "SELECT value 
		        FROM " . $this->session_table . " 
				WHERE sesskey = '" . $this->DB->Slashes($sesskey) . "' 
				AND expiry > '" . time() . "' 
				LIMIT 1"; 
        $query = $this->DB->Query($sql); 

        $num_rows = $this->DB->NumRows($query); 
        if ($num_rows > 0) { 
            $data = $this->DB->FetchArray($query); 
            $session_data = $data["value"]; 
            return $session_data; 
        } else { 
            return ''; 
        } 
    } # end function

    function _write($key, $value) { 

		$expiry = time() + $this->session_lifetime;
		
		$sql = "SELECT COUNT(*) as total 
				FROM " . $this->session_table . " 
				WHERE sesskey = '" . $this->DB->Slashes($key) . "'";
		$check_query = $this->DB->Query($sql);
		$check = $this->DB->FetchArray($check_query);
		
		if ($check['total'] > 0) {
			$update_sql = "UPDATE " . $this->session_table . " 
						   SET expiry = '" . $this->DB->Slashes($expiry) . "', value = '" . $this->DB->Slashes($value) . "' 
						   WHERE sesskey = '" . $this->DB->Slashes($key) . "'";
			return $this->DB->Query($update_sql);
		} else {
			$insert_sql = "INSERT INTO " . $this->session_table . " values ('" . $this->DB->Slashes($key) . "', '" . $this->DB->Slashes($expiry) . "', '" . $this->DB->Slashes($value) . "')";
			return $this->DB->Query($insert_sql);
		}
    } # end function


    function _destroy($sesskey) { 
        $delete_sql = "DELETE FROM " . $this->session_table . " WHERE sesskey = '$sesskey'"; 
        return $this->DB->Query($delete_sql); 
    } # end function

    function _gc() { 
    	return $this->DB->Query("DELETE FROM " . $this->session_table . " where expiry < '" . time() . "'");
    } # end function 

} # end class

class MySQL_DataBase{
	/**
 	* Database host (localhost, IP based, etc)
	* @var string
 	*/
	var $host;
	/**
 	* Database user
	* @var string
 	*/
	var $user;
	/**
 	* Database name
	* @var string
 	*/
	var $db;
	/**
 	* Database password
	* @var string
 	*/
	var $pass;
	/**
 	* Database link
	* @var resource
 	*/
	var $link_id;


	function MySQL_DataBase($host, $user, $db, $pass){
		$this->host = $host;
		$this->user = $user;
		$this->db = $db;
		$this->pass = $pass;		
		$this->ConnectDB();
		$this->SelectDB();
	} # end function

/**
 * Function to connect to MySQL 
 * @author Bobby Easland 
 * @version 1.1
 */	
	function ConnectDB(){
		$this->link_id = mysql_connect($this->host, $this->user, $this->pass);
	} # end function
	

	function SelectDB(){
		return mysql_select_db($this->db);
	} # end function

	function Query($query){
		return @mysql_query($query, $this->link_id);
	} # end function
	

	function FetchArray($resource_id, $type = MYSQL_BOTH){
		return @mysql_fetch_array($resource_id, $type);
	} # end function
	

	function NumRows($resource_id){
		return @mysql_num_rows($resource_id);
	} # end function

	function InsertID() {
		return mysql_insert_id();
	}
	

	function Free($resource_id){
		return @mysql_free_result($resource_id);
	} # end function

	function Slashes($data){
		return addslashes($data);
	} # end function

} # end class
?>